import javax.servlet.http.HttpServletResponse

class SmsController {

  def index = { redirect(action: incoming, params: params) }

  def incoming = {
    String smsSender = params.sender
    Date  smsDate = new Date()
    try {smsDate = new Date(1000 * Long.valueOf(params.time))} catch (Exception e) {}
    String smsText = params.text
    String smsSystem = params.system
    log.info "New SMS received: sender: '$smsSender', time: '$smsDate', text: '$smsText', system: '$smsSystem'"
    def responseText = ''
    
    if (smsSender && smsText && smsDate) {
      def profile = Profile.findByPrivateMobile(smsSender)
      if (!profile) profile = Profile.findByBusinessMobile(smsSender)
      if (profile) {
        def msg = new Message(user: profile.user, content: smsText, medium: "MoTS SMS Aggregator", dateCreated: smsDate).save()
        responseText = "SMS successfully published with message id ${msg.id}"
        response.setStatus(HttpServletResponse.SC_OK)
        log.debug responseText
      } else {
        responseText = "Sender $smsSender not found in the members list. Skipping SMS publication."
        response.setStatus(HttpServletResponse.SC_FORBIDDEN)
        log.warn responseText
      }
    } else {
      responseText = "Request incomplete: sender: '$smsSender', time: '$smsDate', text: '$smsText', system: '$smsSystem'"
      response.setStatus(HttpServletResponse.SC_BAD_REQUEST)
      log.warn responseText
    }
    render responseText
  }
}
